﻿#include "Enemy.h"
#include "enemy/EnemyManager.h"
#include <math.h>
#include <iostream>
#include "utils/AudioUtil.h"
using namespace cocos2d;
using namespace cocos2d::ui;
using namespace cocostudio::timeline;

Enemy::Enemy(EnemyType enemyType, EnemyLevel enemyLevel):
	moveSpeed(30),
	enemyType(enemyType),
	enemyLevel(enemyLevel),
	live(true)
{
	//scaleLevel = {};
	//hp = enemyLevel * pow(8 - enemyLevel, (double)enemyLevel);
	int level = UserDefault::getInstance()->getIntegerForKey("num_2", 1);
	hp = 20 + enemyLevel * 20 + level * 5;
	provideCoin = enemyLevel * 100;
}

Enemy* Enemy::create(EnemyType enemyType, EnemyLevel enemyLevel) {
	Enemy* ret = new (std::nothrow) Enemy(enemyType, enemyLevel);
	if (ret && ret->init()) {
		ret->autorelease();
		return ret;
	}
	CC_SAFE_DELETE(ret);
	return nullptr;
}

bool Enemy::init() {
	if (!Widget::init()) {
		return false;
	}
	size = Director::getInstance()->getVisibleSize();
	initCsbNode();
	initSpriteFrameCache();
	initEnemy();
	initActDir();
	runAct();
	scheduleUpdate();
	schedule(schedule_selector(Enemy::slowTimeUpdate), 1, -1, 0);
	return true;
}

/*
	加载csb文件
*/
void Enemy::initCsbNode() {
	char filename[80];
	sprintf_s(filename, "scenes/game/enemy_ui/enemy_%d_%d.csb", enemyType, enemyLevel);
	//加载csb文件
	root = CSLoader::createNode(filename);
	this->addChild(root);
	//用来测试的调度器
	//scheduleOnce(schedule_selector(Enemy::testUpdate), 8);
}

/*
	初始化病毒
*/
void Enemy::initEnemy() {
	enemyBody = dynamic_cast<Sprite*>(root->getChildByName("enemyClothes"));
	//enemyBody->setAnchorPoint(Vec2::ZERO);
	enemyDie = dynamic_cast<Sprite*>(root->getChildByName("enemyDie"));
	enemyDie->setVisible(false);
	hp_text = dynamic_cast<TextAtlas*>(root->getChildByName("hp_text"));
	enemySize = enemyBody->getContentSize();
	//根据等级缩放病毒大小
	root->setScale(scaleLevel[enemyLevel-1]);
	//设置血量
	hp_text->setString(std::to_string(hp));
	//设置初始化移动方向
	if (enemyPos.x > size.width / 2) {
		dir = Vec2(-1, -1);//设置往左下飞行方向
	} else {
		dir = Vec2(1, -1);//设置往右下飞行方向
	}
}

/*
	运行动画
*/
void Enemy::runAct() {
	char filename[80];
	sprintf_s(filename, "scenes/game/enemy_ui/enemy_%d_%d.csb", enemyType, enemyLevel);
	ActionTimeline* enemyAct = CSLoader::createTimeline(filename);
	//播放某个动作 参数：1.动作的名字 2.是否循环
	enemyAct->play("run", true);
	//指定节点播放动作
	root->runAction(enemyAct);
}

/*
	播放病毒死亡动画
*/
void Enemy::playEnemyDieAction() {
	
	enemyDie->setVisible(true);
	//隐藏其他节点
	Sprite* enemy_0 = dynamic_cast<Sprite*>(root->getChildByName("enemy_0"));
	Sprite* enemy_1 = dynamic_cast<Sprite*>(root->getChildByName("enemy_1"));
	enemy_0->setVisible(false);
	enemy_1->setVisible(false);
	enemyBody->setVisible(false);
	hp_text->setVisible(false);
	char filename[80];
	sprintf_s(filename, "scenes/game/enemy_ui/enemy_%d_%d.csb", enemyType, enemyLevel);
	ActionTimeline* enemyDieAct = CSLoader::createTimeline(filename);
	enemyDieAct->play("enemyDie", false);
	enemyDieAct->setAnimationEndCallFunc("enemyDie", [this]() {
		//回收自己
		EnemyManager::getInstance()->collection(this);
	});
	root->runAction(enemyDieAct);
}

/*
	初始化运动方向
*/
void Enemy::initActDir() {
	float x = root->getPositionX();
	if (x >= size.width / 2) {
		dir = Vec2(-1, -1);
	} else {
		dir = Vec2(1, -1);
	}
}

/*
	病毒移动调度器
*/
void Enemy::update(float dt) {
	if (moveSpeed == EnemySpeed::Normal) {
		if (slowTime > 0) {
			moveSpeed = 10 + (6 - enemyLevel) * 5;
		} else {
			moveSpeed = 20 + (6 - enemyLevel) * 10;
		}
	}

	if (!live) {
		//病毒死亡关闭调度器
		return;
	} else {
		hp_text->setString(std::to_string(hp));
	}
	Vec2 pos = root->getPosition();
	if (pos.x <= -enemyPos.x + enemySize.width / 4) {
		dir = Vec2(1, -1);//设置往右下飞行方向
	} else if (pos.x > size.width - enemyPos.x - enemySize.width / 4) {
		dir = Vec2(-1, -1);//设置往左下飞行方向
	}
	if (pos.y < -enemyPos.y - enemySize.height / 4) {//如果病毒从屏幕上消失，则让它回到屏幕的最高处
		pos.y = enemySize.height / 4 + size.height - enemyPos.y;
	}
	enemyCurrentPos = pos;
	root->setPosition(pos + dir * dt * moveSpeed);
}

/*
	测试用的调度器
*/
void Enemy::testUpdate(float dt) {
}

void Enemy::slowTimeUpdate(float dt) {
	if (slowTime > 0) {
		slowTime--;
	}
}
/*
	用于缓存plist文件
*/
void Enemy::initSpriteFrameCache() {
	enemySpriteCache = SpriteFrameCache::getInstance();
	enemySpriteCache->addSpriteFramesWithFile("scenes/game/image/enemy_0.plist",
		Director::getInstance()->getTextureCache()->addImage(
			"scenes/game/image/enemy_0.png"));		//向帧缓冲中添加纹理图片
}

/*
	病毒受攻击
*/
void Enemy::hurt(int atk)//受伤
{
	hp -= atk;
	moveSpeed = 10 + (6 - enemyLevel) * 5;
	if (hp <= 0)//当血量<=0时,hp=0
	{
		hp = 0;
		die();
	}
}

/*
	病毒死亡
*/
void Enemy::die() {
	AudioUtil::getInstence()->enemyDesyEff();
	//分发病毒死亡的消息
	_eventDispatcher->dispatchCustomEvent("onEnemyDeath", this);
	live = false;
	playEnemyDieAction();
}

/*
	返回自己的Rect
*/
Rect Enemy::getEnemyRect() {
	float x = convertToWorldSpace(root->getPosition()).x - 50;
	float y = convertToWorldSpace(root->getPosition()).y;
	float width = enemySize.width * scaleLevel[enemyLevel - 1] * 0.45;
	float height = enemySize.height * scaleLevel[enemyLevel - 1] * 0.45;
	return Rect(x, y, width, height);
}